import { Http } from "../../utils/http"
import { config } from "../../config/config";

Page({

  data: {
    couponList: [],
    arr: []

  },

  //生命周期函数--监听页面加载
  onLoad: function (options) {
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: `${config.apiBaseUrl}wechat/index/login`,
          data: {
            code: res.code,
          },
          success: (res) => {
            // console.log(res);  
            wx.setStorageSync('token', res.data.data.token);
            // console.log(wx.getStorageSync('token'));
            
            if (Object.prototype.toString.call(options.scene) !== '[object Undefined]') {//获取 扫码进来的场景值
              // console.log('ok');
              let arr = decodeURIComponent(options.scene).split(",");
              if (arr[0] == '9527') {
                this.ongetCoupon(arr[1]);
              }
            }
            this.ongetCont();
          }
        });
      }
    })
  },

  ongetCont: async function () {
    let result = await Http.request({
      url: 'wechat/coupon/get_coupon_by_user',
      data: { token: wx.getStorageSync('token') },
      method: "GET"
    });
    console.log(result.msg);
    if (result.code == 0) {
      //得到优惠券ID
      this.setData({ couponList: result.data });
      // wx.showModal({
      //   title: '提示',
      //   content: result.msg
      // });
    } else {
      wx.showModal({
        title: '提示',
        content: '购买飞花令即可获得分享机会',
        success: function (res) {
          if (res.cancel) {
            //点击取消,默认隐藏弹框
          } else {
            //console.log("点击确定");
            //点击确定
            wx.switchTab({
              url: '/pages/home/index',
            });
          }
        }
      });
    }
  },
  
  ongetCoupon: async function (coup) {//获取优惠券
    let result = await Http.request({
      url: 'wechat/coupon/get_d_coupon',
      data: { stock: coup },
      method: "GET"
    });
    console.log(result);
    if (result.code == 0) {
      
    } else {
      wx.showModal({
        title: '提示',
        content: result.msg
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    console.log(e.target.dataset.id);
    return {
      title: '好闺蜜！送你一份小惊喜',
      path: '/pages/run/index?scene=' + e.target.dataset.id,
      imageUrl: 'https://img01.yzcdn.cn/upload_files/2021/05/03/Fi6DGCCc5i5Y2x3eeZxY2wQlWUEp.png'
    }
  }
})